02. Block-Level Scope

Block-Level Scope

Question:

In the last example, we looked at function-level syntax, which is common for programming languages. In this example, we're going to examine how JavaScript does not include block-level scope.

Blocks, like if-statements and any of the loops you've learned about, do not create their own scope.

Your Challenge

In this quiz, you will encounter a snippet of code with two console.logs. Try to predict the results of each!

Click "Continue to quiz" when you're ready to give it a shot!

Start Quiz:

Solution:

var outsideExample = "First string";
if (true) {
    var outsideExample = "Second string";
    console.log(outsideExample);
}
console.log(outsideExample);

The first console.log() obviously logs "Second string" as it comes right after we set the value of outsideExample to "Second string". But what about the second console.log()?

Remember, if statements do not create their own scope. Unlike the last quiz, where we created a totally new variable inside a function, the if statement does not create a new variable. It simply overwrites the value of outsideExample to "Second string".

So, the second time we console.log(), we see "Second string" again.

INSTRUCTOR NOTE:

Follow your instructors!

@cwpittman

+jameswilliams

As always, it's a good idea to try this out for yourself! Here's the code so you can copy/paste it into the console.

var outsideExample = "First string";
if (true) {
    var outsideExample = "Second string";
    console.log(outsideExample);
}
console.log(outsideExample);